import axios from "axios";
import { Message, MessageBox, Notification, Loading } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";
import errorCode from "@/utils/errorCode";
import { tansParams } from "@/utils/ruoyi";

axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
axios.defaults.withCredentials = true;
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时
  timeout: 0,
});

// loading框设置局部刷新，且所有请求完成后关闭loading框
let loading;
function startLoading() {
  // loading = Loading.service({
  //   fullscreen: false,
  //   text:'加载中...',
  //   background: "rgba(0, 0, 0, 0)",
  // });
  // Message('正在获取数据...')
}
function endLoading() {
  // loading.close();
  // Message.success('数据加载成功')

}
// 声明一个对象用于存储请求个数
let needLoadingRequestCount = 0;
function showFullScreenLoading() {
  if (needLoadingRequestCount === 0) {
    startLoading();
  }
  needLoadingRequestCount++;
}
function tryHideFullScreenLoading() {
  if (needLoadingRequestCount <= 0) return;
  needLoadingRequestCount--;
  if (needLoadingRequestCount === 0) {
    endLoading();
  }
}

// request拦截器
service.interceptors.request.use(
  (config) => {
    if (!config.noLoading) {
      showFullScreenLoading();
    }
    // 是否需要设置 token
    const isToken = (config.headers || {}).isToken === false;
    if (getToken() && !isToken) {
      config.headers["Authorization"] = "Bearer " + getToken(); // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    // 拦截需要添加communityId的接口
    if (config.curCommunity && config.curCommunity.communityId) {
      let _curCommunity = store.getters["community/getCurCommunity"];
      if (_curCommunity) {
        switch (config.method) {
          case "get":
            config.params.communityId = _curCommunity.communityId;
            break;
          case "post":
            config.data.communityId = _curCommunity.communityId;
            break;
        }
      } else {
        switch (config.method) {
          case "get":
            config.params.communityId = "-1";
            break;
          case "post":
            config.data.communityId = "-1";
            break;
        }
      }
    }
    // get请求映射params参数
    if (config.method === "get" && config.params) {
      let url = config.url + "?";
      for (const propName of Object.keys(config.params)) {
        const value = config.params[propName];
        var part = encodeURIComponent(propName) + "=";
        if (value !== null && typeof value !== "undefined") {
          if (typeof value === "object") {
            for (const key of Object.keys(value)) {
              let params = propName + "[" + key + "]";
              var subPart = encodeURIComponent(params) + "=";
              url += subPart + encodeURIComponent(value[key]) + "&";
            }
          } else {
            url += part + encodeURIComponent(value) + "&";
          }
        }
      }
      url = url.slice(0, -1);
      config.params = {};
      config.url = url;
    }
    return config;
  },
  (error) => {
    tryHideFullScreenLoading();
    console.log(error);
    Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    tryHideFullScreenLoading();
    // 未设置状态码则默认成功状态
    // console.log(res);
    let code = 200;
    if (!res.data.status) {
      code = 200;
    } else {
      code = res.data.status.code || 200;
    }
    // console.log(res.data);
    // 获取错误信息
    let msg = "";
    if (res.data.status) {
      msg =
        errorCode[code] ||
        res.data.status.msg ||
        res.data.status.message ||
        errorCode["default"];
    }

    const { message } = res.data.status || "";
    // console.log(code);
    if (code === 401) {
      MessageBox.alert(
        "登录状态已过期，您可以继续留在该页面，或者重新登录",
        "系统提示",
        {
          confirmButtonText: "确定",
          callback: (action) => {
            store.dispatch("LogOut").then(() => {
              location.href = "/index";
            });
          },
        }
      );
    } else if (code === 500) {
      tryHideFullScreenLoading();
      Message({
        message: msg,
        type: "error",
      });
      return Promise.reject(new Error(msg));
    } else if (code !== 200) {
      Notification.error({
        title: message,
      });
      return Promise.reject("error");
    } else {
      // console.log(res);
      if (res.headers["content-type"] === "application/octet-stream") {
        return res;
      }
      // console.log(res.data);
      // 没有数据返回的
      // if (JSON.stringify(res.data) == "{}") {
      //   // Message({
      //   //   message: '参数错误',
      //   //   type: 'error'
      //   // })
      //   return false;
      //   return Promise.reject(new Error(msg));
      // }
      // 返回500 token 失效了
      if (res.data.error) {
        if (
          (res.data.error.code == 500 &&
            res.data.error.message == "invalid token supplied") ||
          (res.data.error.code == 401 &&
            res.data.error.message ==
              "token verification failed: token expired")
        ) {
          store.dispatch("LogOut").then(() => {
            location.href = "/index";
          });
          return Promise.reject(new Error(msg));
        }
      }
      // 表明后端返回文件流
      if (
        res.headers["content-type"] === "application/vnd.ms-excel;charset=utf-8"
      ) {
        return res;
      }
      return res.data.data;
    }
  },
  (error) => {
    tryHideFullScreenLoading();
    console.log("err" + error);
    let { message } = error;
    if (message === "Network Error") {
      return false;
      // message = "服务器开了点小差，请刷新重试";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    Message({
      message: message,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

// 通用下载方法
export function download(url, params, method) {
  let serviceMethod;
  if (method.toLowerCase() === "get") {
    serviceMethod = service.get(url, {
      responseType: "blob",
    });
  } else {
    serviceMethod = service.post(url, params, {
      transformRequest: [
        (params) => {
          return tansParams(params);
        },
      ],
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      responseType: "blob",
    });
  }
  return serviceMethod
    .then((data) => {
      return Promise.resolve(data);
    })
    .catch((r) => {
      console.error(r);
    });
}

export default service;
